package com.wuzuqing.android.eightdiagrams.base

import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView

abstract class BaseAdapter<T>(var layoutId: Int) : RecyclerView.Adapter<BaseViewHolder>() {
    protected var mDataList = mutableListOf<T>()
    var mOnItemClickListener: OnItemClickListener<T>? = null
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(getLayoutId(viewType), parent, false)

        return BaseViewHolder(itemView).also { holder ->
            itemView.setOnClickListener {
                val position = holder.adapterPosition
                mOnItemClickListener?.onItemClick(getItem(position)!!, position)
                onClickPosition(position)
            }
        }
    }

    fun setOnItemClickListener(listener: OnItemClickListener<T>?) {
        mOnItemClickListener = listener
    }

    open fun getLayoutId(viewType: Int): Int {
        return layoutId
    }

    open fun onClickPosition(position: Int) {

    }

    fun getItem(position: Int): T? {
        if (mDataList.isEmpty()){
            return null
        }
        return mDataList[position]
    }

    override fun getItemCount(): Int {
        return mDataList.size
    }

   open fun setList(list: MutableList<T>) {
        mDataList.clear()
        mDataList.addAll(list)
        notifyDataSetChanged()
    }

    open fun performClickItem(position: Int){
        onClickPosition(position)
    }

    interface OnItemClickListener<T> {
        fun onItemClick(data: T, position: Int)
    }
}

class BaseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    val views = SparseArray<View>()

    fun <T> getView(id: Int): T {
        var view = views[id]
        if (view == null) {
            view = itemView.findViewById(id)
            views[id] = view
        }
        return view as T
    }

    fun setText(id:Int,text:CharSequence){
        getView<TextView>(id).text = text
    }

}